package com.microlecture.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.microlecture.common.DataPacket;
import com.microlecture.entity.*;
import com.microlecture.service.*;
import com.microlecture.utils.LoginUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 数据请求
 * Created by 孙志伟 on 2018/5/24.
 */
@RestController
public class DataRequestController {

    @Autowired
    private CookbookCollectService cookbookCollectService;

    /**
     * 收藏食谱
     * @param cookbookid
     * @return
     */
    @RequestMapping("/collectCookbook")
    public Map<String, Object> collectCookbook(
            @RequestParam("cookbookid") Integer cookbookid) {

        if(LoginUtils.isSessionInvalid()) {
            return DataPacket.sessionInvalidJsonResult();
        }
        List<CookbookCollect> cookbookCollects = cookbookCollectService.selectByCondition(LoginUtils.getCurrentUserInfo().getId(), cookbookid);
        //没有，就收藏
        if(cookbookCollects.size() == 0) {
            CookbookCollect cookbookCollect = new CookbookCollect();
            cookbookCollect.setUserid(LoginUtils.getCurrentUserInfo().getId());
            cookbookCollect.setCookbookid(cookbookid);
            cookbookCollectService.insertSelective(cookbookCollect);
            return DataPacket.jsonCode("1");
        } else {
            //有，删除
            cookbookCollectService.deleteByPrimaryKey(cookbookCollects.get(0).getId());
            return DataPacket.jsonCode("0");
        }
    }

    @Autowired
    private ShopCartService shopCartService;

    /**
     * 购物车
     * @param cookbookid
     * @return
     */
    @RequestMapping("/shopCart")
    public Map<String, Object> shopCart(@RequestParam("cookbookid") Integer cookbookid) {

        if(LoginUtils.isSessionInvalid()) {
            return DataPacket.sessionInvalidJsonResult();
        }
        List<ShopCart> shopCarts = shopCartService.selectByCondition(LoginUtils.getCurrentUserInfo().getId(), cookbookid);
        //没有，就收藏
        if(shopCarts.size() == 0) {
            ShopCart shopCart = new ShopCart();
            shopCart.setUserid(LoginUtils.getCurrentUserInfo().getId());
            shopCart.setCookbookid(cookbookid);
            shopCartService.insertSelective(shopCart);
            return DataPacket.jsonCode("1");
        } else {
            //有，删除
            shopCartService.deleteByPrimaryKey(shopCarts.get(0).getId());
            return DataPacket.jsonCode("0");
        }
    }

    @Autowired
    private CookbookDiscussService cookbookDiscussService;

    @Autowired
    private UserService userService;

    /**
     * 弹幕
     * @param cookbookid
     * @return
     */
    @RequestMapping("/bulletScreen")
    public List<String> bulletScreen(@RequestParam("cookbookid") Integer cookbookid) {
        List<String> bullet = new ArrayList<>();
        List<CookbookDiscuss> cookbookDiscusses = cookbookDiscussService.selectByCondition(null, cookbookid);
        for(CookbookDiscuss cookbookDiscuss : cookbookDiscusses) {
            UserEntity userEntity = userService.selectByPrimaryKey(cookbookDiscuss.getUserid());
            bullet.add(userEntity.getNick() + "：" + cookbookDiscuss.getContent());
        }
        return bullet;
    }

    /**
     * 评论
     * @param cookbookid
     * @return
     */
    @RequestMapping("/discuss")
    public Map<String, Object> discuss(@RequestParam("cookbookid") Integer cookbookid,
                                @RequestParam("content") String content) {
        if(LoginUtils.isSessionInvalid()) {
            return  DataPacket.sessionInvalidJsonResult();
        }
        CookbookDiscuss cookbookDiscuss = new CookbookDiscuss();
        cookbookDiscuss.setUserid(LoginUtils.getCurrentUserInfo().getId());
        cookbookDiscuss.setCookbookid(cookbookid);
        cookbookDiscuss.setContent(content);
        cookbookDiscuss.setDiscusstime(new Date());
        return DataPacket.changeDBResult(cookbookDiscussService.insertSelective(cookbookDiscuss));
    }

    @Autowired
    private FoodService foodService;

    /**
     * 评论
     * @return
     */
    @RequestMapping("/foodList")
    public List<Food> foodList() {
        List<Food> foods = foodService.selectList();
        return foods;
    }

    @Autowired
    private CookbookService cookbookService;

    @Autowired
    private CookbookFoodService cookbookFoodService;

    @Autowired
    private CookbookStepService cookbookStepService;

    /**
     * 评论
     * @return
     */
    @RequestMapping("/publishCookBookInfo")
    @Transactional
    public Map<String, Object> publishCookBookInfo(HttpServletRequest request) {
        if(LoginUtils.isSessionInvalid()) {
            return DataPacket.sessionInvalidJsonResult();
        }
        String cookbookname = request.getParameter("cookbookname");
        String appropriatecrowd = request.getParameter("appropriatecrowd");
        String style = request.getParameter("style");
        String craft = request.getParameter("craft");
        String taste = request.getParameter("taste");
        String duration = request.getParameter("duration");
        String difficulty = request.getParameter("difficulty");
        String coverimg = request.getParameter("coverimg");
        //食谱基本信息
        Cookbook cookbook = new Cookbook();
        Integer cookbookId = (int) (new Date().getTime());
        cookbook.setId(cookbookId);
        cookbook.setUserid(LoginUtils.getCurrentUserInfo().getId());
        cookbook.setCookbookname(cookbookname);
        cookbook.setStyle(style);
        cookbook.setAppropriatecrowd(appropriatecrowd);
        cookbook.setCraft(craft);
        cookbook.setTaste(taste);
        cookbook.setDuration(duration);
        cookbook.setDifficulty(difficulty);
        cookbook.setCoverimg(coverimg);
        cookbook.setCreatedate(new Date());
        int insertSelective = cookbookService.insertSelective(cookbook);
        if(insertSelective < 0) {
            return DataPacket.errorJsonResult();
        }
        boolean insertSuccess = true;
        //食材
        List<Integer> cookbookFoodList = new ArrayList<>();
        try {
            int i = 0;
            while (true) {
                String foodid = request.getParameter("food"+i);
                if(StringUtils.isEmpty(foodid)) {
                    break;
                }
                cookbookFoodList.add(Integer.parseInt(foodid));
                i ++;
            }
        } catch (Exception e) {}
        //插入食材
        for(Integer foodId : cookbookFoodList) {
            CookbookFood cookbookFood = new CookbookFood();
            cookbookFood.setCookbookid(cookbookId);
            cookbookFood.setFoodid(foodId);
            int weight = 30 + new Random().nextInt(80);
            cookbookFood.setWeight(weight);
            int selective = cookbookFoodService.insertSelective(cookbookFood);
            if(selective < 0) {
                insertSuccess = false;
            }
        }

        //步骤
        List<String> stepContentList = new ArrayList<>();
        try {
            int i = 0;
            while (true) {
                String stepContent = request.getParameter("stepcontent"+i);
                if(StringUtils.isEmpty(stepContent)) {
                    break;
                }
                stepContentList.add(stepContent);
                i ++;
            }
        } catch (Exception e) {}

        //步骤图
        List<String> stepimgList = new ArrayList<>();
        try {
            int i = 0;
            while (true) {
                String stepimg = request.getParameter("stepimg"+i);
                if(StringUtils.isEmpty(stepimg)) {
                    break;
                }
                stepimgList.add(stepimg);
                i ++;
            }
        } catch (Exception e) {}

        //步骤
        for(int i = 0; i < stepContentList.size(); i ++) {
            CookbookStep cookbookStep = new CookbookStep();
            cookbookStep.setCookbookid(cookbookId);
            cookbookStep.setOrder(i+1);
            cookbookStep.setStepcontent(stepContentList.get(0));
            cookbookStep.setStepimg(stepimgList.get(0));
            int selective = cookbookStepService.insertSelective(cookbookStep);
            if(selective < 0) {
                insertSuccess = false;
            }
        }
        if(insertSuccess) {
            return DataPacket.jsonResult();
        } else {
            return DataPacket.errorJsonResult();
        }
    }


}
